const canvas = document.getElementById('whiteboard');
const ctx = canvas.getContext('2d');
let objects = []; // {type: 'image', x, y, width, height, originalWidth, originalHeight, scale, data}
let selectedObjectIndex = null;
let draggingObject = false;
let dragOffsetX = 0, dragOffsetY = 0;

// --------- Whiteboard Data Persistence ---------
function saveWhiteboardData() {
  // Save image objects
  const imageData = objects.map(obj => {
    if (obj.type === 'image') {
      // Convert image to base64
      const canvasTmp = document.createElement('canvas');
      canvasTmp.width = obj.originalWidth;
      canvasTmp.height = obj.originalHeight;
      canvasTmp.getContext('2d').drawImage(obj.data, 0, 0);
      return {
        type: 'image',
        x: obj.x,
        y: obj.y,
        width: obj.width,
        height: obj.height,
        originalWidth: obj.originalWidth,
        originalHeight: obj.originalHeight,
        scale: obj.scale,
        dataURL: canvasTmp.toDataURL()
      };
    }
    return null;
  }).filter(Boolean);

  // Save text divs
  const textData = Array.from(document.querySelectorAll('.draggable-text')).map(div => ({
    type: 'text',
    html: div.innerHTML,
    left: div.style.left,
    top: div.style.top,
    width: div.style.width,
    height: div.style.height
  }));

  if (window.chrome && chrome.storage && chrome.storage.local) {
    chrome.storage.local.set({
      whiteboardImages: imageData,
      whiteboardTexts: textData
    });
  } else {
    // fallback for non-extension environment
    localStorage.setItem('whiteboardImages', JSON.stringify(imageData));
    localStorage.setItem('whiteboardTexts', JSON.stringify(textData));
  }
}

function restoreWhiteboardData() {
  function doRestore(images, texts) {
    // Restore images
    objects = [];
    if (images) {
      images.forEach(imgObj => {
        const img = new Image();
        img.onload = function() {
          objects.push({
            type: 'image',
            x: imgObj.x,
            y: imgObj.y,
            width: imgObj.width,
            height: imgObj.height,
            originalWidth: imgObj.originalWidth,
            originalHeight: imgObj.originalHeight,
            scale: imgObj.scale,
            data: img
          });
          redraw();
        };
        img.src = imgObj.dataURL;
      });
    }
    // Restore texts
    if (texts) {
      texts.forEach(txt => {
        const div = document.createElement('div');
        div.className = 'draggable-text';
        div.contentEditable = true;
        div.innerHTML = txt.html;
        div.style.position = 'absolute';
        div.style.left = txt.left;
        div.style.top = txt.top;
        if (txt.width) div.style.width = txt.width;
        if (txt.height) div.style.height = txt.height;
        div.style.minWidth = '40px';
        div.style.minHeight = '24px';
        div.style.cursor = 'move';
        div.style.zIndex = 10;
        document.body.appendChild(div);
        makeDivDraggable(div);
      });
    }
  }
  if (window.chrome && chrome.storage && chrome.storage.local) {
    chrome.storage.local.get(['whiteboardImages', 'whiteboardTexts'], function(result) {
      doRestore(result.whiteboardImages, result.whiteboardTexts);
    });
  } else {
    // fallback for non-extension environment
    const images = JSON.parse(localStorage.getItem('whiteboardImages') || '[]');
    const texts = JSON.parse(localStorage.getItem('whiteboardTexts') || '[]');
    doRestore(images, texts);
  }
}

// --------- Responsive Canvas (no overflow) ---------
function resizeCanvas() {
  const toolbarHeight = document.getElementById('toolbar').offsetHeight;
  canvas.width = window.innerWidth;
  canvas.height = window.innerHeight - toolbarHeight;
  canvas.style.display = 'block';
  canvas.style.position = 'absolute';
  canvas.style.left = '0';
  canvas.style.top = toolbarHeight + 'px';
  canvas.style.width = window.innerWidth + 'px';
  canvas.style.height = (window.innerHeight - toolbarHeight) + 'px';
  document.body.style.overflow = 'hidden';
  redraw();
}
window.addEventListener('resize', resizeCanvas);
resizeCanvas();

// --------- Style toolbar buttons ---------
const clearBtn = document.getElementById('clear-btn');
clearBtn.className = 'button';

const addTextBtn = document.createElement('button');
addTextBtn.textContent = 'Add Text';
addTextBtn.id = 'add-text-btn';
addTextBtn.className = 'button primary-button';
document.getElementById('toolbar').appendChild(addTextBtn);
addTextBtn.onclick = () => {
  createTextDiv('Double-click to edit text');
  saveWhiteboardData();
};

// --------- 通用通知方法 ---------
function showNotification(message, type = 'success', duration = 3000) {
  const notification = document.getElementById('notification');
  const notificationMessage = document.getElementById('notification-message');
  notificationMessage.textContent = message;
  notification.className = 'notification ' + type;
  notification.classList.add('show');
  setTimeout(() => {
    notification.style.animation = 'notification-hide 0.4s forwards';
    setTimeout(() => {
      notification.classList.remove('show');
      notification.style.animation = '';
    }, 400);
  }, duration);
}

// --------- 清空确认弹窗逻辑 ---------
const confirmDialog = document.getElementById('confirm-dialog');
const cancelClearBtn = document.getElementById('cancel-clear');
const confirmClearBtn = document.getElementById('confirm-clear');

clearBtn.onclick = () => {
  confirmDialog.style.display = 'flex';
};
cancelClearBtn.onclick = () => {
  confirmDialog.style.display = 'none';
};
confirmClearBtn.onclick = () => {
  // Remove all text divs
  document.querySelectorAll('.draggable-text').forEach(div => {
    div.remove();
  });
  // 清空图片对象
  objects = [];
  selectedObjectIndex = null;
  // 失去所有焦点
  if (document.activeElement) document.activeElement.blur();
  // 清空画布
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  saveWhiteboardData();
  redraw();
  confirmDialog.style.display = 'none';
  showNotification('Whiteboard cleared', 'success');
};

function createTextDiv(html) {
  const div = document.createElement('div');
  div.className = 'draggable-text';
  div.contentEditable = true;
  div.innerHTML = html;
  div.style.position = 'absolute';
  div.style.left = (window.innerWidth / 2 - 100) + 'px';
  div.style.top = (window.innerHeight / 2 - 30) + 'px';
  div.style.minWidth = '40px';
  div.style.minHeight = '24px';
  div.style.cursor = 'move';
  div.style.zIndex = 10;
  document.body.appendChild(div);
  makeDivDraggable(div);
  div.focus();
}

// --------- Paste image and rich text ---------
document.addEventListener('paste', function (e) {
  // Rich text (HTML)
  const html = e.clipboardData.getData('text/html');
  if (html) {
    createTextDiv(html);
    saveWhiteboardData();
    e.preventDefault();
    return;
  }
  // Image
  if (e.clipboardData && e.clipboardData.items) {
    for (let item of e.clipboardData.items) {
      if (item.type.indexOf('image') !== -1) {
        const file = item.getAsFile();
        const img = new Image();
        img.onload = function () {
          const obj = {
            type: 'image',
            x: (canvas.width - img.width) / 2,
            y: (canvas.height - img.height) / 2,
            width: img.width,
            height: img.height,
            originalWidth: img.width,
            originalHeight: img.height,
            scale: 1,
            data: img
          };
          objects.push(obj);
          saveWhiteboardData();
          redraw();
        };
        img.src = URL.createObjectURL(file);
        e.preventDefault();
        return;
      }
    }
  }
});

// --------- Image scaling (mouse wheel) ---------
canvas.addEventListener('wheel', function(e) {
  if (selectedObjectIndex !== null && objects[selectedObjectIndex].type === 'image') {
    e.preventDefault();
    const obj = objects[selectedObjectIndex];
    let scale = obj.scale || 1;
    scale += e.deltaY < 0 ? 0.1 : -0.1;
    scale = Math.max(0.1, Math.min(10, scale));
    obj.scale = scale;
    obj.width = obj.originalWidth * scale;
    obj.height = obj.originalHeight * scale;
    saveWhiteboardData();
    redraw();
  }
});

// --------- Delete selected object ---------
document.addEventListener('keydown', function (e) {
  // Delete selected image
  if (e.key === 'Delete' && selectedObjectIndex !== null) {
    objects.splice(selectedObjectIndex, 1);
    selectedObjectIndex = null;
    saveWhiteboardData();
    redraw();
  }
});

// --------- Redraw all ---------
function redraw() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  // Draw all images
  for (let i = 0; i < objects.length; i++) {
    const obj = objects[i];
    if (obj.type === 'image') {
      ctx.drawImage(obj.data, obj.x, obj.y, obj.width, obj.height);
      if (i === selectedObjectIndex) drawSelection(obj);
    }
  }
}

// --------- Helper: get object at position ---------
canvas.addEventListener('mousedown', e => {
  const objIdx = getObjectAt(e.offsetX, e.offsetY);
  if (objIdx !== null) {
    selectedObjectIndex = objIdx;
    draggingObject = true;
    dragOffsetX = e.offsetX - objects[objIdx].x;
    dragOffsetY = e.offsetY - objects[objIdx].y;
    redraw();
    return;
  }
  selectedObjectIndex = null;
  redraw();
});
canvas.addEventListener('mousemove', e => {
  if (draggingObject && selectedObjectIndex !== null) {
    const obj = objects[selectedObjectIndex];
    obj.x = e.offsetX - dragOffsetX;
    obj.y = e.offsetY - dragOffsetY;
    saveWhiteboardData();
    redraw();
    return;
  }
});
canvas.addEventListener('mouseup', () => {
  draggingObject = false;
});
canvas.addEventListener('mouseleave', () => {
  draggingObject = false;
});

function getObjectAt(x, y) {
  for (let i = objects.length - 1; i >= 0; i--) {
    const obj = objects[i];
    if (obj.type === 'image') {
      if (x >= obj.x && x <= obj.x + obj.width && y >= obj.y && y <= obj.y + obj.height) {
        return i;
      }
    }
  }
  return null;
}

function drawSelection(obj) {
  ctx.save();
  ctx.strokeStyle = '#0078ff';
  ctx.lineWidth = 2;
  ctx.strokeRect(obj.x, obj.y, obj.width, obj.height);
  ctx.restore();
}

// --------- Make text div draggable ---------
function makeDivDraggable(div) {
  let isDragging = false;
  let offsetX = 0, offsetY = 0;
  div.addEventListener('mousedown', function(e) {
    isDragging = true;
    offsetX = e.clientX - div.offsetLeft;
    offsetY = e.clientY - div.offsetTop;
    div.style.zIndex = 20;
    document.body.style.userSelect = 'none';
  });
  document.addEventListener('mousemove', function(e) {
    if (!isDragging) return;
    div.style.left = (e.clientX - offsetX) + 'px';
    div.style.top = (e.clientY - offsetY) + 'px';
    saveWhiteboardData();
  });
  document.addEventListener('mouseup', function() {
    isDragging = false;
    div.style.zIndex = 10;
    document.body.style.userSelect = '';
  });
  // Delete on Delete key
  div.addEventListener('keydown', function(e) {
    if (e.key === 'Delete') {
      div.remove();
      saveWhiteboardData();
    }
  });
  // 保存内容变更
  div.addEventListener('input', function() {
    saveWhiteboardData();
  });
}

// --------- Init ---------
restoreWhiteboardData();
redraw(); 

// Go Home 按钮跳转
const goHomeBtn = document.getElementById('go-home-btn');
if (goHomeBtn) {
  goHomeBtn.onclick = function() {
    window.location.href = 'home.html';
  };
} 